document.addEventListener('DOMContentLoaded', function() {
  const userMenu = document.getElementById('userMenu');
  const dropdownMenu = document.getElementById('dropdownMenu');
  const usernameDisplay = document.getElementById('usernameDisplay');
  const logoutBtn = document.getElementById('logout');

  // 只查sessionStorage
  let username = sessionStorage.getItem('username');
  if (!username) {
    if (userMenu) userMenu.style.display = 'none';
  } else {
    if (userMenu) userMenu.style.display = '';
    usernameDisplay.textContent = username;
  }

  // 退出登录时清除所有存储并隐藏userMenu
  if (logoutBtn) {
    logoutBtn.addEventListener('click', function() {
      localStorage.clear();
      sessionStorage.clear();
      sessionStorage.removeItem('isLoggedIn');
      if (userMenu) userMenu.style.display = 'none';
    });
  }

  // 切换下拉菜单显示
  if (userMenu) {
    userMenu.addEventListener('click', function(e) {
      e.stopPropagation();
      userMenu.classList.toggle('open');
    });
  }

  // 点击页面其他地方关闭菜单
  document.addEventListener('click', function() {
    if (userMenu) userMenu.classList.remove('open');
  });

  // 防止点击菜单内容时关闭
  if (dropdownMenu) {
    dropdownMenu.addEventListener('click', function(e) {
      e.stopPropagation();
    });
  }

  // 个人空间跳转
  const profileLink = document.getElementById('profileLink');
  if (profileLink) {
    profileLink.addEventListener('click', function(e) {
      e.preventDefault();
      window.location.href = 'profile.html';
    });
  }

  // 首页功能区按钮日志输出
  if (window.location.pathname.endsWith('index.html') || window.location.pathname === '/' || window.location.pathname === '/index.html') {
    document.querySelectorAll('.feature-card .btn').forEach(function(btn) {
      btn.addEventListener('click', function(e) {
        const card = btn.closest('.feature-card');
        const title = card ? card.querySelector('h3')?.textContent?.trim() : '';
        console.log(`[功能跳转] ${title} -> ${btn.getAttribute('href')}`);
      });
    });
  }

  // 首页普通用户数量统计显示
  if (document.getElementById('normalUserCount')) {
      fetch('http://localhost:3000/api/guest-visit')
          .then(res => res.json())
          .then(data => {
              document.getElementById('normalUserCount').textContent = data.normalUserCount;
          });
  }

  // 数据导入弹窗逻辑
  const openImportModalBtn = document.getElementById('openImportModalBtn');
  const importModal = document.getElementById('importModal');
  const closeImportModalBtn = document.getElementById('closeImportModalBtn');
  const importForm = document.getElementById('importForm');
  const importResult = document.getElementById('importResult');

  if (openImportModalBtn && importModal && closeImportModalBtn && importForm) {
    openImportModalBtn.onclick = function() {
      importModal.style.display = 'flex';
      importForm.reset();
      importResult.innerHTML = '';
    };
    closeImportModalBtn.onclick = function() {
      importModal.style.display = 'none';
    };
    importModal.onclick = function(e) {
      if (e.target === importModal) importModal.style.display = 'none';
    };
    importForm.onsubmit = async function(e) {
      e.preventDefault();
      importResult.innerHTML = '';
      const table = document.getElementById('importTable').value;
      const fileInput = document.getElementById('importFile');
      if (!table) {
        importResult.innerHTML = '<span style="color:#d32f2f;">请选择要导入的表！</span>';
        return;
      }
      if (!fileInput.files || fileInput.files.length === 0) {
        importResult.innerHTML = '<span style="color:#d32f2f;">请选择Excel文件！</span>';
        return;
      }
      const file = fileInput.files[0];
      const formData = new FormData();
      formData.append('table', table);
      formData.append('file', file);
      importResult.innerHTML = '<span style="color:#388e3c;">正在导入，请稍候...</span>';
      try {
        const res = await fetch('/api/import', {
          method: 'POST',
          headers: { 'Authorization': sessionStorage.getItem('token') || '' },
          body: formData
        });
        const data = await res.json();
        if (res.ok) {
          importResult.innerHTML = '<span style="color:#388e3c;">导入成功，共导入 '+(data.count||0)+' 条数据！</span>';
        } else {
          importResult.innerHTML = '<span style="color:#d32f2f;">导入失败：'+(data.error||'数据字段不符合')+'</span>';
        }
      } catch (err) {
        importResult.innerHTML = '<span style="color:#d32f2f;">导入失败，服务器异常</span>';
      }
    };
  }
}); 